package me.cxlr.qinlauncher2.dao;

import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.Sort;
import me.cxlr.qinlauncher2.model.App;
import me.cxlr.qinlauncher2.model.Folder;

/**
 * AppDao
 *
 * @author 酷安用户:山轮纸
 */
public class AppDao {
    private Realm realm;

    /**
     * 保存
     *
     * @param appList 当前设备内的应用
     */
    public void saveApp(List<App> appList) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        realm.beginTransaction();
        List<App> tmpList = realm.copyToRealm(appList);
        realm.commitTransaction();
        realm.close();
    }

    /**
     * 修改
     *
     * @param app App
     */
    public void updateApp(App app) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        realm.beginTransaction();
        App tmp = realm.copyToRealmOrUpdate(app);
        realm.commitTransaction();
        realm.close();
    }

    /**
     * 修改
     *
     * @param appList appList
     */
    public void updateApp(List<App> appList) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        realm.beginTransaction();
        List<App> tmp = realm.copyToRealmOrUpdate(appList);
        realm.commitTransaction();
        realm.close();
    }

    /**
     * 删除
     *
     * @param packageName 包名
     */
    public void deleteApp(String packageName) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        realm.beginTransaction();
        RealmResults<App> appList = realm.where(App.class).equalTo("packageName", packageName).findAll();
        if (appList.size() > 0) {
            for (App entity : appList) {
                entity.deleteFromRealm();
            }
        }
        realm.commitTransaction();
        realm.close();
    }

    /**
     * 删除
     *
     * @param packageName 包名
     * @param clazzName   活动名
     */
    public void deleteApp(String packageName, String clazzName) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        realm.beginTransaction();
        RealmResults<App> appList = realm.where(App.class)
                .equalTo("packageName", packageName)
                .and()
                .equalTo("clazzName", clazzName)
                .findAll();
        if (appList.size() > 0) {
            for (App entity : appList) {
                entity.deleteFromRealm();
            }
        }
        realm.commitTransaction();
        realm.close();
    }

    /**
     * 查询全部App
     *
     * @return 全部App
     */
    public List<App> findAllApp() {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        RealmResults<App> results = realm.where(App.class).findAll();
        assert results != null;
        List<App> appList = realm.copyFromRealm(results.sort(new String[]{"appType", "appDrawer.sorting"}, new Sort[]{Sort.DESCENDING, Sort.ASCENDING}));
        realm.close();
        return appList;
    }

    /**
     * 根据id查询
     *
     * @param id 主键
     * @return App
     */
    public App findAppById(String id) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        App results = realm.where(App.class)
                .equalTo("id", id)
                .findFirst();
        assert results != null;
        App tmp = realm.copyFromRealm(results);
        realm.close();
        return tmp;
    }

    /**
     * 获取不在文件夹内的、非隐藏的 App
     *
     * @param sorting 排序
     * @return 不在文件夹内的、非隐藏的 App
     */
    public List<App> findAppListByNotInFolder(int sorting, int systemAppSorting) {
        List<App> appList = new ArrayList<>(16);
        try {
            realm = Realm.getInstance(RealmConfig.getRealmConfig());
            RealmResults<App> results = realm.where(App.class)
                    .equalTo("appDrawer.hidden", false)
                    .and()
                    .equalTo("appDrawer.inFolder", false)
                    .findAll();
            if (results != null) {
                // 系统app依照应用排序
                if (systemAppSorting == 0) {
                    if (sorting == 0) {
                        appList = realm.copyFromRealm(results.sort("appDrawer.sorting", Sort.ASCENDING));
                        realm.close();
                    } else {
                        appList = realm.copyFromRealm(results.sort("appDrawer.sorting", Sort.DESCENDING));
                    }
                }
                // 系统应用在用户安装的之前
                else if (systemAppSorting == 1) {
                    if (sorting == 0) {
                        appList = realm.copyFromRealm(results.sort(new String[]{"appType", "appDrawer.sorting"}, new Sort[]{Sort.DESCENDING, Sort.ASCENDING}));
                        realm.close();
                    } else {
                        appList = realm.copyFromRealm(results.sort(new String[]{"appType", "appDrawer.sorting"}, new Sort[]{Sort.DESCENDING, Sort.DESCENDING}));
                    }
                }
                // 系统应用在用户安装的之后
                else if (systemAppSorting == 2) {
                    if (sorting == 0) {
                        appList = realm.copyFromRealm(results.sort(new String[]{"appType", "appDrawer.sorting"}, new Sort[]{Sort.ASCENDING, Sort.ASCENDING}));
                        realm.close();
                    } else {
                        appList = realm.copyFromRealm(results.sort(new String[]{"appType", "appDrawer.sorting"}, new Sort[]{Sort.ASCENDING, Sort.DESCENDING}));
                    }
                }

            }
            return appList;
        } catch (Exception e) {
            Logger.e("getAppListByNotInFolder:" + e.toString());
            return appList;
        } finally {
            realm.close();
        }
    }

    /**
     * 查询文件夹内的所有App
     *
     * @param folder 文件夹
     * @return 文件夹内的所有App
     */
    public List<App> findAppInFolder(Folder folder) {
        try {
            realm = Realm.getInstance(RealmConfig.getRealmConfig());
            RealmResults<App> results = realm.where(App.class)
                    .equalTo("appDrawer.folder.id", folder.getId())
                    .and()
                    .equalTo("appDrawer.inFolder", true)
                    .findAll();
            List<App> appList = realm.copyFromRealm(results.sort("appDrawer.sortingInFolder", Sort.ASCENDING));
            return appList;
        } catch (Exception e) {
            Logger.e("findAppInFolder:" + e.toString());
            return null;
        } finally {
            realm.close();
        }
    }

    /**
     * 根据文件夹id和文件夹排序,查询文件夹内的app
     *
     * @param folder          文件夹
     * @param sortingInFolder 文件夹排序
     * @return 文件夹内的app
     */
    public App findAppInFolderBySortingInFolder(Folder folder, int sortingInFolder) {
        realm = Realm.getInstance(RealmConfig.getRealmConfig());
        App results = realm.where(App.class)
                .equalTo("appDrawer.folder.id", folder.getId())
                .and()
                .equalTo("appDrawer.sortingInFolder", sortingInFolder)
                .findFirst();
        assert results != null;
        App tmp = realm.copyFromRealm(results);
        realm.close();
        return tmp;
    }

    /**
     * 查询隐藏应用
     *
     * @return 隐藏应用
     */
    public List<App> findHiddenApp() {
        List<App> appList = new ArrayList<>(16);
        try {
            realm = Realm.getInstance(RealmConfig.getRealmConfig());
            RealmResults<App> results = realm.where(App.class)
                    .equalTo("appDrawer.hidden", true)
                    .findAll();
            if (results != null) {
                appList = realm.copyFromRealm(results.sort(new String[]{"appType", "appDrawer.sorting"}, new Sort[]{Sort.DESCENDING, Sort.ASCENDING}));
            }
            return appList;
        } catch (Exception e) {
            Logger.e("findHiddenApp:" + e.toString());
            return appList;
        } finally {
            realm.close();
        }
    }

    /**
     * 根据包名查询
     *
     * @param packageName 包名
     * @return List<App>
     */
    public List<App> findAppByPackageName(String packageName) {
        List<App> appList = new ArrayList<>(16);
        try {
            realm = Realm.getInstance(RealmConfig.getRealmConfig());
            RealmResults<App> results = realm.where(App.class)
                    .equalTo("packageName", packageName)
                    .findAll();
            if (results != null) {
                appList = realm.copyFromRealm(results.sort("appDrawer.sorting", Sort.ASCENDING));
            }
            return appList;
        } catch (Exception e) {
            Logger.e("findAppByPackageName:" + e.toString());
            return appList;
        } finally {
            realm.close();
        }
    }

    /**
     * 根据包名和活动名查询App
     *
     * @param packageName 包名
     * @param clazzName   活动名
     * @return App
     */
    public App findAppByPackageNameAndClazzName(String packageName, String clazzName) {
        try {
            realm = Realm.getInstance(RealmConfig.getRealmConfig());
            App result = realm.where(App.class)
                    .equalTo("packageName", packageName)
                    .and()
                    .equalTo("clazzName", clazzName)
                    .findFirst();
            if (result != null) {
                return realm.copyFromRealm(result);
            } else {
                return null;
            }
        } catch (Exception e) {
            Logger.e("findAppByPackageNameAndClazzName:" + e.toString());
            return null;
        } finally {
            realm.close();
        }
    }

    /**
     * 根据包名和活动名查看是否有这个App
     *
     * @param packageName 包名
     * @param clazzName   活动名
     * @return appCount
     */
    public int hasAppCount(String packageName, String clazzName) {
        int appCount = 0;
        try {
            realm = Realm.getInstance(RealmConfig.getRealmConfig());
            RealmResults<App> results = realm.where(App.class)
                    .equalTo("packageName", packageName)
                    .and()
                    .equalTo("clazzName", clazzName)
                    .findAll();
            if (results != null) {
                List<App> appList = realm.copyFromRealm(results.sort("appDrawer.sorting", Sort.ASCENDING));
                appCount = appList.size();
            }
            return appCount;
        } catch (Exception e) {
            Logger.e("hasAppCount:" + e.toString());
            return 0;
        } finally {
            realm.close();
        }
    }
}
